package io.traveller.apiGateway.server.filter.pre;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.traveller.apiGateway.server.filter.FilterType;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 处理zuulRequestHeader的Filter
 * 1. 设置请求host：
 * 原因：tomcat不支持X-Forwarded-Host，重定向使用host，返回Header为Location的值会为http://ip:port/path的情况。
 * 解决：使用nginx传递来的host，设置到zuulRequestHeader
 * <p>
 * Created by yunai on 16/9/22.
 */
public class PreRequestHeaderFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterType.PRE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            switch (headerName) {
                case "host": {
                    String value = request.getHeader(headerName);
                    if (StringUtils.hasText(value)) {
                        ctx.getZuulRequestHeaders().put("host", value);
                    }
                    break;
                }
            }
        }
        return null;
    }

}
